package demo.web.xxx;

import com.just_bean.JustBeanApplication;
import com.just_bean.core.bean.BaseBean;
import com.just_bean.core.handler.AnnoHandler;
import demo.test.anno.LogTs;
import demo.test.handler.LogTsHandler;
import demo.web.WebApplication;
import demo.web.anno.Controller;
import demo.web.anno.PostMapper;
import demo.web.bean.ControllerBean;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo {
    public static void main(String[] args) throws Exception {
        // 创建web响应框架
        WebApplication webApplication = new WebApplication();

        // 创建justBean
        Map<Class<? extends Annotation>, AnnoHandler> handlerMap = new HashMap<>();
        handlerMap.put(LogTs.class, new LogTsHandler());

        Map<Class<? extends Annotation>, Class<? extends BaseBean>> beanClzMap = new HashMap<>();
        beanClzMap.put(Controller.class, ControllerBean.class);

        JustBeanApplication application = JustBeanApplication.emptyApp(Demo.class, handlerMap, beanClzMap);

        List<? extends BaseBean> beanList = application.listBeanWithAnnotation(Controller.class);
        // 整合层代码
        for (BaseBean bean : beanList) {
            Object instance = bean.get();
            Class clz = bean.getClz();
            Controller controller = (Controller) clz.getAnnotation(Controller.class);
            final String pre = controller.value();
            for (Method method : clz.getMethods()) {
                PostMapper postMapper = method.getAnnotation(PostMapper.class);
                if (postMapper == null) continue;
                String url = pre + postMapper.value();
                webApplication.register(url, req -> (String) method.invoke(instance));
            }
        }

        webApplication.start();
    }
}
